﻿using System;
using BigBank.Contracts.Base.V1.Aspects;
using BigBank.Contracts.Base.V1.Messages;
using BigBank.Contracts.Logging.V1.Clients;
using BigBank.Contracts.Logging.V1.Interfaces;
using BigBank.Contracts.Logging.V1.Services;

namespace BigBank.Contracts.Base.V1
{
    namespace Services
    {
        [SetExecutionTime]
        [SetDefaultCorrelationId]
        [WrapExceptionsInFaults]
        partial class BaseServiceBase
        {
            public ILoggingServiceClient LoggingServiceClient { get; set; }

            protected BaseServiceBase()
            {
                LoggingServiceClient = new LoggingServiceClient(new LoggingServiceProxy());
            }

            protected BaseServiceBase(ILoggingServiceClient loggingServiceClient)
            {
                LoggingServiceClient = loggingServiceClient;

                PreBaseServiceOperation += OnPreBaseServiceOperation;
                PostBaseServiceOperation += OnPostBaseServiceOperation;
                BaseServiceOperationError += OnBaseServiceOperationError;
            }

            private void OnPreBaseServiceOperation(ref BaseServiceRequest request)
            {
                LoggingServiceClient.Debug(string.Format("[{0}] Request of type {1} has started execution at {2}",
                                                         request.CorrelationId, request.GetType().Name,
                                                         request.ExecutionStart));
            }

            private void OnPostBaseServiceOperation(ref BaseServiceRequest request, ref BaseServiceResponse response)
            {
                LoggingServiceClient.Debug("[" + request.CorrelationId + "] Request of type " + request.GetType().Name +
                                           " finished processing. Execution time was " +
                                           response.ExecutionTime.TotalMilliseconds);
            }

            private void OnBaseServiceOperationError(ref BaseServiceRequest request, ref Exception exception)
            {
                LoggingServiceClient.Error("[" + request.CorrelationId + "] " + exception);
            }
        }
    }
}